import { App } from "vue"

export function imgReal(app:App) {
  app.directive('real-url', {
      async beforeMount(el, binding) {
          const imgUrl = binding.value
          if(imgUrl){
              const exist = await imageIsExist(imgUrl)
              exist && el.setAttribute('src', imgUrl)
          }
          function imageIsExist(url:string) {
              return new Promise(resolve => {
                  let img:any = new Image()
                  img.src = url
                  img.onload = () => {
                      if(img.complete){
                          resolve(true)
                          img = null;
                      }
                  }
                  img.onerror = () => {
                      resolve(false);
                      img = null;
                  }
              })
          }
      }
  })
}